package 多线程.线程交替打印;

/**
 * @author zx
 * @create 2022-09-10 16:30
 */
public class 使用sync_wait_notify {
    public static void main(String[] args) {
        Object o = new Object();
        char[] arr1 = "1234567".toCharArray();
        char[] arr2 = "ABCDEFG".toCharArray();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : arr1) {
                        System.out.print(c);
                        try {
                            o.notify();
                            o.wait(); //让出锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify(); //必须，否则无法停止程序
                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : arr2) {
                        System.out.print(c);
                        try {
                            o.notify();
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify();
                }
            }
        };
        t1.start();
        t2.start();
    }

    /**
     * 方式二：使用lambada表达式
     */
    public static void main2(String[] args) {
        final Object o = new Object();
        char[] aI = "1234567".toCharArray();
        char[] aC = "ABCDEFG".toCharArray();
        new Thread(() -> {
            synchronized (o) {
                for (char c : aI) {
                    System.out.print(c);
                    try {
                        o.notify();
                        o.wait(); //让出锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify(); //必须，否则无法停止程序
            }
        }, "t1").start();
        new Thread(() -> {
            synchronized (o) {
                for (char c : aC) {
                    System.out.print(c);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        }, "t2").start();
    }
}
